<template>
  <view class="approval-dialog" v-if="visible" @click="handleClose">
    <view class="dialog-content" @click.stop>
      <!-- 头部 -->
      <view class="dialog-header">
        <text class="header-title">{{ dialogTitle }}</text>
        <text class="close-btn" @click="handleClose">×</text>
      </view>

      <!-- 内容区域 -->
      <scroll-view class="dialog-body" scroll-y>
        <!-- 审批操作选择 -->
        <view class="form-section">
          <view class="section-title">
            <text>审批操作</text>
            <text class="required">*</text>
          </view>
          <view class="radio-group">
            <view
              class="radio-item"
              :class="{ active: formData.action === 'approve' }"
              @click="formData.action = 'approve'"
            >
              <view class="radio-icon">
                <text v-if="formData.action === 'approve'">✓</text>
              </view>
              <text class="radio-label">同意</text>
            </view>
            <view
              class="radio-item"
              :class="{ active: formData.action === 'reject' }"
              @click="formData.action = 'reject'"
              v-if="canReject"
            >
              <view class="radio-icon">
                <text v-if="formData.action === 'reject'">✓</text>
              </view>
              <text class="radio-label">拒绝</text>
            </view>
          </view>
        </view>

        <!-- 退回步骤选择（领导批示且拒绝时显示） -->
        <view class="form-section" v-if="showRejectStepSelector">
          <view class="section-title">
            <text>退回步骤</text>
            <text class="required">*</text>
          </view>
          <view class="step-button-group">
            <view
              v-for="(option, index) in rejectOptions"
              :key="index"
              class="step-button"
              :class="{ active: formData.rejectNextStep === option.value }"
              @click="selectRejectStep(option.value, index)"
            >
              <text>{{ option.label }}</text>
            </view>
          </view>
        </view>

        <!-- 审批意见（文本输入 + 手写签名） -->
        <view class="form-section">
          <view class="section-title">
            <text>审批意见</text>
          </view>

          <!-- 文本输入 (无签名时显示) -->
          <textarea
            v-if="!signaturePath"
            v-model="formData.opinion"
            class="opinion-input"
            placeholder="请输入审批意见"
            :maxlength="200"
            auto-height
          />
          <view v-if="!signaturePath" class="char-count">
            <text>{{ formData.opinion.length }}/200</text>
          </view>

          <!-- 手写签名区域 -->
          <view class="signature-area">
            <view class="signature-header">
              <text class="sub-label">手写意见 (可选)</text>
              <view class="signature-btn" @click="openSignaturePad">
                <u-icon name="edit-pen" size="16" color="#1a3582"></u-icon>
                <text>{{ signaturePath ? '重新签名' : '点击签名' }}</text>
              </view>
            </view>

            <view v-if="signaturePath" class="signature-preview-box">
              <image
                :src="signaturePath"
                mode="aspectFit"
                class="signature-img"
                @click="previewSignature"
              />
              <view class="clear-signature" @click.stop="clearStoredSignature">
                <u-icon name="close-circle-fill" size="24" color="#ef4444"></u-icon>
              </view>
            </view>
          </view>
        </view>

        <!-- 提示信息 -->
        <view class="tips-section" v-if="isSecretaryStep">
          <text class="tips-icon">💡</text>
          <text class="tips-text">文秘步骤自动填写"-"，无需输入意见</text>
        </view>
      </scroll-view>

      <!-- 底部操作按钮 -->
      <view class="dialog-footer">
        <view class="footer-btn cancel" @click="handleClose">
          <text>取消</text>
        </view>
        <view
          class="footer-btn confirm"
          :class="{ disabled: !canSubmit || submitLoading }"
          @click="handleSubmit"
        >
          <text>{{ submitLoading ? '提交中...' : '确认提交' }}</text>
        </view>
      </view>
    </view>

    <!-- 手写签名弹窗 -->
    <u-popup
      :show="showSignature"
      mode="center"
      width="100%"
      height="100%"
      :border-radius="0"
      :mask-close-able="false"
      @close="closeSignaturePad"
    >
      <view class="signature-popup-container">
        <view class="popup-header">
          <text class="title">请在下方区域手写审批意见</text>
          <u-icon name="close" size="32" @click="closeSignaturePad"></u-icon>
        </view>

        <view class="signature-content">
          <l-signature
            ref="signatureRef"
            :penColor="'#000000'"
            :penSize="5"
            :openSmooth="true"
            disableScroll
            landscape
          ></l-signature>
        </view>

        <view class="popup-footer">
          <view class="btn reset" @click="handleSignatureClear">
            <u-icon name="reload" size="28"></u-icon>
            <text>重写</text>
          </view>
          <view class="btn confirm" @click="handleSignatureConfirm">
            <u-icon name="checkmark" size="28"></u-icon>
            <text>确认使用</text>
          </view>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { uploadFile } from '@/Api/request'

// Props
const props = defineProps<{
  visible: boolean
  documentId: number | null
  stepOrder: number
  currentStepName: string
  nextStepName: string
  rejectRecords?: Array<{
    nextStep: string
    nextStepName?: string
  }>
  canReject?: boolean // 是否可以拒绝（科室步骤不能拒绝）
}>()

// Emits
const emit = defineEmits<{
  'update:visible': [value: boolean]
  confirm: [
    data: {
      action: 'approve' | 'reject'
      opinion: string // 文字意见
      signature?: string // 签名图片路径
      rejectNextStep?: string
    },
  ]
  close: []
}>()

// 签名相关状态
const showSignature = ref(false)
const signatureRef = ref<any>(null)
const signaturePath = ref('') // 签名图片路径

// 表单数据
const formData = ref({
  action: 'approve' as 'approve' | 'reject',
  opinion: '', // 文字意见
  rejectNextStep: '',
})

// 提交加载状态
const submitLoading = ref(false)

// 退回步骤选择索引
const rejectStepIndex = ref(0)

// 对话框标题
const dialogTitle = computed(() => {
  return `审批 - ${props.currentStepName || '未知步骤'}`
})

// 是否为文秘步骤
const isSecretaryStep = computed(() => {
  return props.currentStepName?.includes('文秘') || false
})

// 是否显示退回步骤选择器
const showRejectStepSelector = computed(() => {
  return (
    formData.value.action === 'reject' &&
    props.currentStepName?.includes('领导批示') &&
    rejectOptions.value.length > 0
  )
})

// 退回选项列表
const rejectOptions = computed(() => {
  return (props.rejectRecords || []).map((r) => ({
    label: r.nextStepName || r.nextStep,
    value: r.nextStep,
  }))
})

// 是否可以提交
const canSubmit = computed(() => {
  if (!formData.value.action) return false

  // 检查意见或签名 (文秘步骤除外)
  const hasOpinion = !!formData.value.opinion.trim() || !!signaturePath.value
  if (!isSecretaryStep.value && !hasOpinion) {
    return false
  }

  // 如果是领导批示且选择拒绝，必须选择退回步骤
  if (showRejectStepSelector.value && !formData.value.rejectNextStep) {
    return false
  }

  return true
})

// 监听visible变化，重置表单
watch(
  () => props.visible,
  (newVal) => {
    if (newVal) {
      formData.value = {
        action: 'approve',
        opinion: '',
        rejectNextStep: '',
      }
      rejectStepIndex.value = 0

      // 如果是文秘步骤，自动填写"-"
      if (isSecretaryStep.value) {
        formData.value.opinion = '-'
      }

      // 如果有退回选项，自动选中第一个
      if (rejectOptions.value.length > 0) {
        formData.value.rejectNextStep = rejectOptions.value[0].value
      }

      // 重置审批意见和签名
      formData.value.opinion = ''
      signaturePath.value = ''
    }
  },
)

// 监听审批操作变化，当切换到拒绝时自动设置第一个退回步骤
watch(
  () => formData.value.action,
  (newAction) => {
    if (newAction === 'reject') {
      // 拒绝时如果意见为空，预填"不同意"
      if (!formData.value.opinion) {
        formData.value.opinion = '不同意'
      }

      if (rejectOptions.value.length > 0) {
        // 如果还没有选择退回步骤，自动选择第一个
        if (!formData.value.rejectNextStep) {
          rejectStepIndex.value = 0
          formData.value.rejectNextStep = rejectOptions.value[0].value
        }
      }
    } else {
      // 同意时如果意见为"不同意"，清空
      if (formData.value.opinion === '不同意') {
        formData.value.opinion = ''
      }
    }
  },
)

// 选择退回步骤
const selectRejectStep = (value: string, index: number) => {
  rejectStepIndex.value = index
  formData.value.rejectNextStep = value
}

// 关闭对话框
const handleClose = () => {
  emit('update:visible', false)
  emit('close')
}

// 打开签名板
const openSignaturePad = () => {
  showSignature.value = true
  // 延时初始化，确保弹窗动画完成
  setTimeout(() => {
    // 如果需要重新初始化可以在这里处理
  }, 300)
}

// 关闭签名板
const closeSignaturePad = () => {
  showSignature.value = false
}

// 清除当前画布
const handleSignatureClear = () => {
  if (signatureRef.value) {
    signatureRef.value.clear()
  }
}

// 清除已保存的签名
const clearStoredSignature = () => {
  signaturePath.value = ''
}

// 预览签名
const previewSignature = () => {
  if (signaturePath.value) {
    uni.previewImage({
      urls: [signaturePath.value],
    })
  }
}

// 确认签名
const handleSignatureConfirm = () => {
  if (signatureRef.value) {
    signatureRef.value.canvasToTempFilePath({
      success: (res: any) => {
        if (res.isEmpty) {
          uni.showToast({
            title: '请先签名',
            icon: 'none',
          })
          return
        }

        // 上传签名图片
        uni.showLoading({ title: '正在保存签名...' })

        uploadFile({
          url: '/system/file/upload',
          filePath: res.tempFilePath,
          name: 'file',
        })
          .then((response: any) => {
            // 解析返回结果
            const fileUrl = response.data?.url

            if (fileUrl) {
              // 保存服务器返回的图片URL
              signaturePath.value = fileUrl
              // 清空文字意见
              formData.value.opinion = ''
              showSignature.value = false
              uni.showToast({ title: '签名已保存', icon: 'success' })
            } else {
              throw new Error('未获取到图片地址')
            }
          })
          .catch((err) => {
            console.error('签名上传失败', err)
            uni.showToast({
              title: '签名保存失败，请重试',
              icon: 'none',
            })
          })
          .finally(() => {
            uni.hideLoading()
          })
      },
      fail: (err: any) => {
        console.error('签名生成失败', err)
        uni.showToast({
          title: '签名生成失败',
          icon: 'none',
        })
      },
    })
  }
}

// 提交审批
const handleSubmit = () => {
  if (!canSubmit.value) {
    if (showRejectStepSelector.value && !formData.value.rejectNextStep) {
      uni.showToast({
        title: '请选择退回步骤',
        icon: 'none',
      })
    } else {
      // 检查意见是否为空
      const hasOpinion = !!formData.value.opinion.trim() || !!signaturePath.value
      if (!isSecretaryStep.value && !hasOpinion) {
        uni.showToast({
          title: '请输入审批意见或手写签名',
          icon: 'none',
        })
        return
      }

      uni.showToast({
        title: '请完善审批信息',
        icon: 'none',
      })
    }
    return
  }

  // 文秘步骤自动填写"-"，其他步骤直接使用审批意见
  const opinion = isSecretaryStep.value ? '-' : formData.value.opinion || ''

  emit('confirm', {
    action: formData.value.action,
    opinion: opinion,
    signature: signaturePath.value, // 传递签名路径
    rejectNextStep: formData.value.rejectNextStep || undefined,
  })
}
</script>

<style lang="scss" scoped>
.approval-dialog {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: 40rpx;

  .dialog-content {
    background: white;
    border-radius: 16rpx;
    width: 90%;
    max-width: 600rpx;
    max-height: 80vh;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    position: relative;
    margin: auto;

    .dialog-header {
      padding: 32rpx;
      border-bottom: 1rpx solid #e5e7eb;
      display: flex;
      justify-content: space-between;
      align-items: center;
      flex-shrink: 0;

      .header-title {
        font-size: 32rpx;
        font-weight: bold;
        color: #1a3582;
      }

      .close-btn {
        font-size: 48rpx;
        color: #9ca3af;
        width: 60rpx;
        height: 60rpx;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }

    .dialog-body {
      flex: 1;
      overflow-y: auto;
      padding: 32rpx;

      .form-section {
        margin-bottom: 32rpx;

        .section-title {
          font-size: 28rpx;
          font-weight: 600;
          color: #374151;
          margin-bottom: 16rpx;

          .required {
            color: #ef4444;
            margin-left: 4rpx;
          }
        }

        .radio-group {
          display: flex;
          gap: 24rpx;

          .radio-item {
            flex: 1;
            height: 88rpx;
            border: 2rpx solid #e5e7eb;
            border-radius: 12rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 12rpx;
            background: white;

            &.active {
              border-color: #1a3582;
              background: #ecf5ff;

              .radio-icon {
                background: #1a3582;
                border-color: #1a3582;

                text {
                  color: white;
                }
              }

              .radio-label {
                color: #1a3582;
                font-weight: 600;
              }
            }

            .radio-icon {
              width: 40rpx;
              height: 40rpx;
              border: 2rpx solid #d1d5db;
              border-radius: 50%;
              display: flex;
              align-items: center;
              justify-content: center;
              background: white;

              text {
                font-size: 24rpx;
                font-weight: bold;
              }
            }

            .radio-label {
              font-size: 28rpx;
              color: #6b7280;
            }
          }
        }

        .step-button-group {
          display: flex;
          gap: 24rpx;

          .step-button {
            flex: 1;
            height: 88rpx;
            border: 2rpx solid #e5e7eb;
            border-radius: 12rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            background: white;

            &.active {
              border-color: #1a3582;
              background: #ecf5ff;

              text {
                color: #1a3582;
                font-weight: 600;
              }
            }

            text {
              font-size: 28rpx;
              color: #6b7280;
            }
          }
        }

        .opinion-input {
          width: 100%;
          min-height: 200rpx;
          padding: 20rpx;
          border: 1rpx solid #e5e7eb;
          border-radius: 12rpx;
          font-size: 28rpx;
          color: #374151;
          background: #f9fafb;
          line-height: 1.6;
        }

        .char-count {
          font-size: 22rpx;
          color: #9ca3af;
          text-align: right;
          margin-top: 8rpx;
          margin-bottom: 16rpx;
        }

        .signature-area {
          border-top: 1rpx dashed #e5e7eb;
          padding-top: 20rpx;

          .signature-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 16rpx;

            .sub-label {
              font-size: 26rpx;
              color: #6b7280;
            }

            .signature-btn {
              display: flex;
              align-items: center;
              gap: 8rpx;
              padding: 10rpx 20rpx;
              background: #eff6ff;
              border-radius: 8rpx;

              text {
                font-size: 24rpx;
                color: #1a3582;
              }
            }
          }

          .signature-preview-box {
            width: 100%;
            height: 200rpx;
            border: 1rpx solid #e5e7eb;
            border-radius: 12rpx;
            background: white;
            position: relative;
            overflow: hidden;
            display: flex;
            align-items: center;
            justify-content: center;

            .signature-img {
              width: 100%;
              height: 100%;
            }

            .clear-signature {
              position: absolute;
              top: 10rpx;
              right: 10rpx;
              z-index: 10;
              padding: 10rpx;
            }
          }
        }
      }

      .tips-section {
        padding: 20rpx 24rpx;
        background: #fffbeb;
        border-radius: 12rpx;
        border: 1rpx solid #fef3c7;
        display: flex;
        align-items: center;
        gap: 12rpx;

        .tips-icon {
          font-size: 32rpx;
          flex-shrink: 0;
        }

        .tips-text {
          flex: 1;
          font-size: 24rpx;
          color: #92400e;
          line-height: 1.5;
        }
      }
    }

    .dialog-footer {
      padding: 24rpx 32rpx;
      border-top: 1rpx solid #e5e7eb;
      display: flex;
      gap: 24rpx;
      flex-shrink: 0;

      .footer-btn {
        flex: 1;
        height: 88rpx;
        border-radius: 12rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 28rpx;
        font-weight: 500;

        &.cancel {
          background: #f3f4f6;
          color: #6b7280;
          border: 1rpx solid #d1d5db;
        }

        &.confirm {
          background: #1a3582;
          color: white;

          &.disabled {
            opacity: 0.5;
            background: #9ca3af;
          }
        }
      }
    }
  }
}

.signature-popup-container {
  width: 100vh;
  height: 100vw;
  background: white;
  display: flex;
  flex-direction: column;

  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%) rotate(90deg);
  transform-origin: center center;
  overflow: hidden; /* 防止内容溢出 */

  .popup-header {
    position: relative; /* 确保在最上层 */
    z-index: 10;
    background: white;
    padding: 24rpx 32rpx 24rpx 44px;
    border-bottom: 1rpx solid #eee;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-shrink: 0;

    .title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }

  .signature-content {
    /* 绝对定位铺满全屏，脱离文档流 */
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
    z-index: 1; /* 在 header/footer 之下 */

    /* 反向旋转 -90 度，恢复坐标系 */
    transform: rotate(-90deg);
    transform-origin: center center;

    /* 旋转后需要重新计算尺寸：旋转后的宽度 = 原高度，旋转后的高度 = 原宽度 */
    /* 由于父容器是 100vh x 100vw（旋转后），我们需要让内容区域占满 */
    /* 使用更大的尺寸确保占满 */
    width: 100vw;
    height: 100vh;
    top: 50%;
    left: 50%;
    margin-left: -50vw;
    margin-top: -50vh;

    background: #f5f5f5;
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: center;

    :deep(l-signature) {
      width: 100% !important;
      height: 100% !important;
    }
  }

  .popup-footer {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 10;
    background: white;
    padding: 24rpx 32rpx;
    border-top: 1rpx solid #eee;
    display: flex;
    flex-direction: row;
    justify-content: center;
    gap: 24rpx;
    width: 100%;
    box-sizing: border-box;

    .btn {
      flex: 1;
      max-width: 200rpx;
      height: 88rpx;
      border-radius: 12rpx;
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: center;
      gap: 8rpx;
      font-size: 28rpx;
      font-weight: 500;

      &.reset {
        background: #f3f4f6;
        color: #666;
        border: 1rpx solid #d1d5db;
      }

      &.confirm {
        background: #1a3582;
        color: white;
      }
    }
  }
}
</style>
